package edu.pku.sei.act.main.project;

import org.eclipse.core.resources.IProject;

import edu.pku.sei.act.model.common.ArchiModel;
import edu.pku.sei.act.model.common.ArchiModelConst;
import edu.pku.sei.act.model.common.ArchiModelFactory;
import edu.pku.sei.gmp.project.exception.ProjectLoadException;
import edu.pku.sei.gmp.project.exception.ProjectSaveException;
import edu.pku.sei.gmp.project.GMPProject;
import edu.pku.sei.gmp.model.common.GMPModel;
import org.eclipse.core.runtime.CoreException;
import edu.pku.sei.gmp.model.xml.GMPXMLSaveLoader;


public class ArchiModelerProject extends GMPProject {
	public static String PROJECT_NATURE = "edu.pku.sei.act.ArchiModeler";
	
	private static final String modelName = "ArchitectureModel";
	
	public ArchiModelerProject(IProject project) {
		super();
		this.project = project;
	}
	
	@Override
	public String getProjectNature() {
		
		return PROJECT_NATURE;
		
	}
	
	@Override
	public void configure() throws CoreException {
	}

	@Override
	public void deconfigure() throws CoreException {
	}
	
	@Override
	public void save() throws ProjectSaveException {
		if (project == null)
			return;
		String parentDir = project.getLocation().toOSString();
		String path = parentDir + "/" + modelName;
		ArchiModel model = getDefaultModel();
		GMPXMLSaveLoader saveLoader = new GMPXMLSaveLoader();
		try {
			saveLoader.save(model, path, ArchiModelConst.__ARCHIMODEL__);
		} catch (Exception e) {
			throw new ProjectSaveException(e);
		}
	}
	
	@Override
	public void load() throws ProjectLoadException {
		initModel();
		
		String parentDir = project.getLocation().toOSString();
		String path = parentDir + "/" + modelName;
		ArchiModel model = getDefaultModel();
		GMPXMLSaveLoader saveLoader = new GMPXMLSaveLoader();
		try {
			saveLoader.load(model, path, ArchiModelConst.__ARCHIMODEL__);
		} catch (Exception e) {
			throw new ProjectLoadException(e);
		}
	}
	
	@Override
	public void initProject() {
		initModel();
		
		//TODO add project initialization code here.
	}
	
	private void initModel() {
		ArchiModelFactory modelFactory = new ArchiModelFactory();
		ArchiModel model = (ArchiModel) modelFactory
				.createModelElement(ArchiModelConst.__ARCHIMODEL__);
		model.setModelFactory(modelFactory);
		modelFactory.setModel(model);
		this.addModel(model);
	}
	
	public ArchiModel getDefaultModel() {
		for (GMPModel model : this.getModels()) {
			if (model instanceof ArchiModel) {
				return (ArchiModel) model;
			}
		}
		return null;
	}
}
